package com.xhs.dto;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Page;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 浏览器会话模型
 *
 * @author xhs
 */
@Data
public class BrowserSession implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 会话ID
     */
    private String sessionId;

    /**
     * 手机号
     */
    private String phoneNumber;

    /**
     * 浏览器实例
     */
    @JsonIgnore
    private Browser browser;

    /**
     * 浏览器上下文
     */
    @JsonIgnore
    private BrowserContext context;

    /**
     * 页面实例
     */
    @JsonIgnore
    private Page page;

    /**
     * 创建时间
     */
    private LocalDateTime createTime;

    /**
     * 最后活动时间
     */
    private LocalDateTime lastActiveTime;

    /**
     * 会话状态
     */
    private SessionStatus status;

    /**
     * 存储的 cookies
     */
    private List<Map<String, Object>> cookies;

    public enum SessionStatus {
        CREATED,          // 已创建
        PHONE_INPUT,      // 已输入手机号
        VERIFY_INPUT,     // 已输入验证码
        LOGIN_SUCCESS,    // 登录成功
        LOGIN_FAILED,     // 登录失败
        EXPIRED,          // 已过期
        CLOSED            // 已关闭
    }

    public BrowserSession(String sessionId, String phoneNumber) {
        this.sessionId = sessionId;
        this.phoneNumber = phoneNumber;
        this.createTime = LocalDateTime.now();
        this.lastActiveTime = LocalDateTime.now();
        this.status = SessionStatus.CREATED;
    }

    /**
     * 更新最后活动时间
     */
    public void updateLastActiveTime() {
        this.lastActiveTime = LocalDateTime.now();
    }

    /**
     * 关闭会话
     */
    public void close() {
        if (page != null && !page.isClosed()) {
            page.close();
        }
        if (context != null) {
            context.close();
        }
        if (browser != null) {
            browser.close();
        }
        this.status = SessionStatus.CLOSED;
    }
} 